Skip to content

Keep path conditions on the old value when a variable is reassigned - #549

Merged
CatarinaGamboa merged 3 commits into
mainfrom
fix/538-keep-path-instances
Nov 23, 2026
Merged

CatarinaGamboa merged 3 commits into
mainfrom
fix/538-keep-path-instances

Conversation

@CatarinaGamboa

@CatarinaGamboa CatarinaGamboa commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #538

What and why

A path condition (the condition of an if, a loop, a ternary) is stored twice: on the variable names (n <= 10 - t) and on the instances the condition was checked on (n@1 <= 10 - t@0). A plain name always means the variable's last instance. Assigning a variable dropped every path condition that mentioned it, so a guard written to keep an assignment in range did not prove it.

Changes:

  1. Keep the condition on the old value. Before a primitive variable gets a new instance (TypeChecker.checkVariableRefinements, used by assignments, +=, ++/-- and declarations; and forgetChanges, used by loop/switch havoc), its name in the path conditions is replaced by its current last instance (VCChecker.keepPathVariablesOnCurrentValue). Conditions are still dropped when the variable has no instance to name its old value, and for objects (they also get new instances on state changes, which do not go through this method).
  2. x++ / x-- no longer keep a stale condition (pre-existing false negative, same root): increments did not touch the path conditions at all, so if (t < 5) { t++; lessThanFive(t); } was accepted on main (t < 5 was read on the incremented value).
  3. Branches no longer leak path conditions (pre-existing false negative, found by the Codex review because (1) made it reachable from an assignment): visitCtIf scanned the else branch with the path conditions the then branch left (e.g. from a nested if (t > 0) return;), and kept both branches' conditions after the if. Now each branch starts from the conditions before the if; after it, only the conditions both branches kept remain, or those of the only branch that reaches the code after the if (as that branch left them, renames included).
  4. Parameters a method writes get an instance for their entry value (pre-existing false negative, found by the Codex review): a refinement that read the parameter before it was written (x == y after int x = y) named the parameter itself, which stands for its last instance, so it changed meaning once y was written (int x = y; if (x > 0) { y = -1; positive(-1); } is accepted on main). snapshotWrittenParameters gives such parameters an entry instance when the method or constructor is checked.

TryChecker is unchanged: after a finally, the name of a variable the finally changed refers to the finally's value, not to the value the try's conditions were checked on, so renaming there would be wrong; dropping stays.

Soundness argument

  • At the moment of the rename, the plain name and the last instance denote the same value (Variable.getRefinement is x == x@last && ...), so the renamed condition says exactly what the condition said just before; instances never change, so it stays true for the rest of the path. Every way a primitive variable gets a new instance either goes through the rename (assignments, increments, declarations, havoc) or happens after the branch assignments that renamed it (if joins, try "any of" instances); a variable declared again in a sibling block gets a new Variable without instances, so conditions on the old name are dropped.
  • Path variables are renamed in place, so removals by identity (removePathVariable, restorePathVariables) still find them; a renamed condition is valid on every path where the original was, including the other branch of an if (the rename names the value from before the if).
  • Branch isolation only removes facts (a branch's own conditions outside its paths); after an if where only one branch continues, that branch's state is the only one that reaches the code after it.
  • Refinements now name a written parameter's entry instance instead of its name, which is the value they were computed from.

Before / after

#538 reproducer (guarded) and early-exit form:

main:   Refinement Error: found `t == #read_result` but expected `t <= 10`   (both forms)
branch: Correct! Passed Verification.
Program main this PR
ErrorGuardedAssignment.incremented (t++ under t < 5) Correct (wrong) Refinement Error
ErrorGuardedAssignment.parameterWrittenAfterCopy Correct (wrong) Refinement Error
ErrorNestedIfPathCondition (both methods) Correct (wrong) Refinement Error (expected t <= 0 but could not prove it)

#537, #479 and the buffer loop from #537 are unchanged by this PR (they need the loop invariant PRs, stacked on this one).

Tests

  • CorrectGuardedAssignment: False error: an if condition that mentions a variable is dropped when that variable is assigned (if (n <= 10 - t) t = t + n) #538's guarded and early-exit forms, and an else branch that uses its condition after the then branch assigned the variable (all fail on main).
  • ErrorGuardedAssignment: the guard is not applied to the new value after an assignment; nor after t++ (accepted on main); nor after an if where only the branch that assigned continues (accepted by a version of this change that reset the condition to its plain-name form at the join); a copy of a parameter keeps its entry value after the parameter is written (accepted on main).
  • ErrorNestedIfPathCondition: a nested if's condition does not hold in the other branch, nor after both branches (both accepted on main).
  • ErrorIfAssignment.ifAssignment2 assigned in a branch that cannot run (a == 5 is never < 0); it is now proved unreachable, so its guard is changed to a > 0 to keep the assignment checked.
  • TestCounterexamples.variableUpdateIncludesNegativeInputAndGeneratedReturn: the counterexample now names the parameter's entry value #x (shown as x; the message is unchanged).

Full suite passes locally (mvn -q test), same wall-clock as main (about 4 min including the build).

🤖 Generated with Claude Code

CatarinaGamboa and others added 2 commits November 23, 2026 13:42
A path condition holds the condition both on variable names and on the
instances it was checked on. Assigning a variable dropped every path
condition that mentioned it, so a guard written to keep the assignment in
range (if (n <= 10 - t) t = t + n) did not prove it. Before a primitive
variable gets a new instance, its name in the path conditions is now
replaced by its current instance, which keeps them true; they are dropped
only when there is no instance to name the old value, or for objects.

This also covers ++ and --, which kept the condition on the name and so
applied it to the incremented value (if (t < 5) { t++; ... } assumed
t < 5 after the increment). After an if where only one branch continues,
the path condition is kept as that branch left it.

ErrorIfAssignment's second case assigned in a branch that cannot run
(a == 5 is never < 0); its guard is changed so the branch is reachable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The else branch started from the path conditions the then branch left,
and both branches' conditions stayed after the if, so a nested
if (t > 0) return; in one branch made t <= 0 known in the other branch
and after the if. Each branch now starts from the conditions before the
if; after it, only the conditions both branches kept remain, or those of
the only branch that reaches the code after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex round 1: what was done

  1. Fixed (real false negative). The root cause was pre-existing: visitCtIf scanned the else branch with the path conditions left by the then branch and kept both branches' conditions after the if. Keeping conditions on assignment made that leak reachable from a program that main rejects. Each branch now starts from the path conditions before the if; after the if only the conditions both branches kept remain, or those of the only branch that continues. Codex's LeakRegression program is now rejected (found y == #read_result but expected y <= 0).
  2. Fixed by the same change (pre-existing). Test: ErrorNestedIfPathCondition (other branch, and after both branches); both methods are accepted on main.
  3. Fixed: the comment on assumeLoopCondition now says that a re-assignment keeps the condition on the old value.

Pushed in 6f9ed76.

A refinement that read a parameter before it was written (x == y after
int x = y) named the parameter itself, and a parameter's name stands for
its last instance: once y was written, x == y described the new value, so
x > 0 and y = -1 contradicted each other and proved anything. A parameter
that the method writes now gets an instance on entry, which such
refinements name.

The counterexample of ErrorAssignmentBeforeReturn names the entry value
#x instead of x (displayed the same).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 2

  1. False negative — newly introduced. The retained path condition can make the verifier’s assumptions inconsistent after a related variable changes:

    import liquidjava.specification.Refinement;
    
    class DependencyOnly {
        static void positive(@Refinement("_ > 0") int a) {}
    
        static void bad(int y) {
            int x = y;
            if (x > 0) {
                x = 0;
                y = -1;
                positive(-1);
            }
        }
    }

    This is reachable with y == 1, and the call violates the annotation. This branch: Correct! Passed Verification. origin/main: Refinement Error: found a == -1 but expected a > 0. The new code retains x’s guard on its old instance, but that instance’s refinement still refers to the mutable plain name y. After y = -1, those facts contradict each other, so the invalid call is proved vacuously. Snapshot mutable dependencies when creating instance refinements, or decline to retain a guard when its old instance has an unsnapshotted mutable dependency. The relevant retention is in VCChecker.java.

    Code quality: visitCtIf saves shallow lists of mutable path variables; rewriting a condition in the then branch also changes the object saved for the else branch. Make branch path predicates immutable or snapshot their refinements as well as list membership. See RefinementTypeChecker.java.

The round 1 fix is verified: in a separate nested-if program, this branch reports errors both in the sibling else and after the join; origin/main incorrectly passes both.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex round 2: what was done

  1. Fixed (false negative). The root cause is pre-existing: a refinement that reads a parameter before the parameter is written (x == y after int x = y) names the parameter itself, which stands for its last instance, so it changes meaning once y is written. Main also accepts it without this PR's change, e.g. int x = y; if (x > 0) { y = -1; positive(-1); } (the guard on x is kept there because it does not mention y). Fix at the root: a parameter that the method writes gets an instance for its entry value when the method is checked (snapshotWrittenParameters), so such refinements name that instance. Codex's DependencyOnly and the variants above are now rejected. Test: ErrorGuardedAssignment.parameterWrittenAfterCopy (accepted on main).
    TestCounterexamples.variableUpdateIncludesNegativeInputAndGeneratedReturn now gets the entry value as #x instead of x; the message shown is unchanged (x == -1).
  2. Declined (code quality: snapshot refinements of the saved path lists). Renaming in place is intended: a rename substitutes a name by the instance holding the value the name had at that point, so the renamed condition is equivalent on every path where the original held, including the other branch (which starts from the same values). Copying the refinements would also break the removals by identity (removePathVariable, restorePathVariables).

Pushed in 73c2c5f.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 3

No new false negative found. The repository was left unchanged. mvn -q compile -pl liquidjava-verifier -am passed.

The earlier fixes held in verifier runs on both builds:

  1. Nested-if fixture: this branch reports both invalid calls; origin/main reports neither.
  2. Guarded-assignment fixtures: this branch reports all four expected errors; origin/main reports two. The valid fixture has no error on this branch and three on main.

Additional assignment and control-flow probes and jump, switch, and finally probes reported the expected violations. I found no code-quality issue in the diff worth a separate finding.

Nothing left to fix; the Codex loop for this PR ends here.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Clean-code review

Audit of this PR's own new code (clean-code-principles: SOLID, DRY, KISS, naming, functions).

  • VCChecker.keepPathVariablesOnCurrentValue - [func-no-side-effects] mutates path variables in place. Declined: intended and documented; the in-place rename keeps identity-based removals working, and a rename is equivalent at the point it happens.
  • TypeChecker.checkVariableRefinements - [solid-srp] now also maintains the path conditions. Declined: it is the one place where a variable gets a new assigned instance, so the path conditions are kept in step there (instead of in each of its four callers, which is how increments were missed before).
  • RefinementTypeChecker.visitCtIf - [func-small] grows by a few lines (branch isolation). Declined: extracting the join logic would be a refactor of an existing long method; the small-PR rule wins.
  • RefinementTypeChecker.snapshotWrittenParameters vs snapshotMutableParameters - [core-dry] both collect the written variables of the executable. Declined: the older one now only matters for conditions on parameters without an entry instance; merging them is a follow-up refactor, not needed for this fix.
  • Removed a dead statement (context.getVariableByName(pathVarName);) and the stale "drops the conditions" comment. Fixed.

@CatarinaGamboa
CatarinaGamboa merged commit 859a161 into main Nov 23, 2026
1 check passed
CatarinaGamboa added a commit that referenced this pull request Nov 23, 2026
Stacked on #549; review/merge after it.

Fixes #543

Part of the loop invariant inference plan (#542).

## What and why
`InvariantCandidates.of(x, x0, condition)` builds the candidate
invariants of an `int` local variable `x` that a loop changes, in the
manner of Liquid Types' qualifiers (Rondon, Kawaguchi, Jhala, PLDI
2008):
- `x >= x0` and `x <= x0`, with `x0` the instance of `x` before the loop
(it only grows or only shrinks; works for symbolic starts);
- the order comparisons (`<`, `<=`, `>`, `>=`) among the top-level
conjuncts of the loop condition that mention `x`, made non-strict so the
iteration that ends the loop can keep them (`i < n` gives `i <= n`).

Terms are limited to integer literals, `int` local variables and
parameters, `+`, `-`, `*` and unary minus: fields and calls may change
out of sight of the loop (PM decision on #542). Comparisons under `||`
or `!` and `!=` give no candidate. Order is deterministic, duplicates
are removed, and there are at most 6 candidates per variable
(`MAX_PER_VARIABLE`, to be tuned in #547).

Pure code, not used by the checker yet; the next PR (Houdini check,
#544) proves the candidates before using them, so a candidate is only a
guess and a wrong one can only cost precision.

## Plan change
The plan had this PR based on `main` and independent of #538. It is
stacked on #549 (#538) instead, so the stack is linear (#549 → this →
#544 → #545): the Houdini step relies on #549 to stay sound (`x++` used
to keep the loop condition on the incremented value, which could prove a
non-inductive candidate), and the buffer loop from #537 then verifies in
the stack itself.

## Tests
`InvariantCandidatesTest` (8 unit tests): bounds from the value before
the loop, none without an instance, weakening of each comparison kind,
only comparisons that mention the variable, none from `||`/`!`/`!=`,
only supported terms (field, call, cast, division, `long` literal
rejected), the grouping of nested terms (`n - (n - 1)`), and the cap.

Full suite passes locally; no change in what the verifier accepts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
CatarinaGamboa added a commit that referenced this pull request Nov 23, 2026
Stacked on #550; review/merge after it.

Fixes #544
Fixes #537
Fixes #479

Part of the loop invariant inference plan (#542).

## What and why
A loop havocs every variable it changes: at the loop head a changed
variable keeps only its declared refinement, so `for (int i = 0; i < 10;
i++) use(i)` did not know `i >= 0` (#537). This PR infers invariants for
the `int` local variables (and parameters) a loop changes, with the
Houdini algorithm (Flanagan and Leino, FME 2001) over the candidates of
#550 (Liquid Types qualifiers):

1. **Start check** (`new LoopInvariants`, before the havoc): keep the
candidates that the facts before the loop prove (`x0` is the instance
before the loop).
2. **Assume at the head** (`startIteration`): add the remaining
candidates to the refinements of the loop-head instances (not as a path
condition, which an assignment would rename or drop).
3. **Step check** (`recordNextIteration`): at the point where the next
iteration starts (end of the body for `while`/for-each, after the update
for `for`, after the condition for `do`-`while`, where the condition is
now assumed since the next iteration only starts when it holds) drop
each candidate not proved for the last instances.
4. **Continues:** the end of a body with continues is a join where
`scanBody` havocs the changed variables again. There, the candidates and
"`x` grew / shrank since the head" are kept when proved at every
continue and at the fall-through end of the body (`atJoin`/`joined`), so
a `for` update or a `do`-`while` condition that follows can still be
checked.
5. Repeat until a check drops nothing, inside the existing
`checkUntilFixpoint` loop (which already re-checks the body until
typestates are stable and keeps only the errors of the last check).
After 8 checks that dropped candidates, all are dropped (`MAX_ROUNDS`).

All candidate proofs are silent (`checkStateSMT(..., silent = true)`); a
failed or unknown proof only drops the candidate. Loops whose jumps run
a `finally` or leave a labelled block (`followsJumps` false) infer
nothing, as their typestates are not followed either.

## Soundness argument
A candidate survives only if (a) it is proved from the facts before the
loop, and (b) in the last check, assuming all survivors at the head, it
is proved at every point where the next iteration starts: the end of the
body (if reachable), the update or condition after it, and every
`continue` (through the join facts, each proved on every path into the
join). So the survivors form an inductive invariant and hold at the head
on every iteration; errors are only kept from that last check. An
earlier check assumes more candidates (and fewer typestates) than the
last one, so an error that stops it is also an error of the last one.
Integers are mathematical, as elsewhere in LiquidJava.

Checked with Codex (no false negative found) and these programs that
must still be rejected: decrementing counter with `_ >= 0`, counter
reset in the body, `i = i - 2` on some path, a bound the step breaks (`i
+= 3` under `i < 10` with `_ <= 10`), a continue path that decreases `i`
(in `while`, and in `for` before the update), an inner loop that
decreases the outer counter, labelled continue from an inner loop,
switch and try/finally in the body.

## Before / after
| Program | main | this PR |
|---|---|---|
| #537 `for (int i = 0; i < 10; i++) use(i)` | `found i < 10 but
expected i >= 0` | Correct |
| #537 `while (total < 1024) { use(total); total = total + 1; }` |
`found total < 1024 but expected total >= 0` | Correct |
| #537 buffer loop (`read(buf, total, limit - total)` with `off >= 0`,
`if (n < 0) break; total += n;`) | `found total < limit but expected
total >= 0` | Correct |
| #538 bounded accumulation (`@Refinement("_ >= 0 && _ <= 1024") total`,
guard then `total = total + n`) | Refinement Error | Correct (with #549)
|
| #479 `for (int i = 0; i < l.size(); i++) l.get(i)` | `... i <
#size_result but expected i >= 0 && i < size(l)` | Correct |

#479 needed only `i >= 0`: the list is not havocked (its `size()` and
`get` do not change its state), so the plan's #546 (candidates from what
the body requires) is not needed for it.

## Tests
- `CorrectLoopInvariants` (each method fails without this PR): #537's
counter and accumulator, the buffer loop, a symbolic start (`for (int i
= k; ...)` after `if (k < 0) return;`), nested loops (`j` starts at
`i`), and a continue in `for`, `while` and `do`-`while`.
- `ErrorLoopInvariants` (non-inductive candidates must not be assumed):
decrementing counter, reset in the body, decreased on some path, bound
not kept by the step, decreased before a continue (in `while`, and in
`for` before the update), decreased in an inner loop.
- `classes/loop_list_index_correct`: the #479 reproducer.

## Timing
Full suite, same machine, two runs each (machine shared, so noisy): main
195 s / 170 s wall, TestExamples 127 s / 86 s; this PR 163 s / 142 s
wall, TestExamples 98 s / 91 s. On the same pair of runs, the 16
existing loop fixtures take 1.3 to 2 times as long (e.g.
`CorrectLoopStateFixpoint` 2.3 s to 3.6 s, `CorrectLoopCondition` 0.37 s
to 0.79 s): each check of a loop body now also runs one silent SMT query
per candidate, and a dropped candidate costs one more check of the body.
Tuning (caps, nested loops re-inferred per outer check) is #547.

## Known precision gaps (from the Codex review, left for later)
- A `for` update or `do`-`while` condition that repairs a value set
before a `continue` (`i = -1; continue;` then `i++`) is not followed:
the join keeps only facts proved before the update.
- A `finally` anywhere on a jump path turns inference off for the whole
loop, as for typestates.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

False error: an if condition that mentions a variable is dropped when that variable is assigned (if (n <= 10 - t) t = t + n)

1 participant